/*
 * @description: 
 * @Author: wzg
 * @Date: 2021-03-18 16:38:06
 * @LastEditTime: 2021-03-19 13:59:28
 */
/* 用于统一处理路由 */
import fs from 'fs';
import path from 'path';
import Router from 'koa-router';
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';
const router = Router();
// const router = require('koa-router')();
let urlArray = [];
/* 获取当前路径的上一级路径 */
const upperLevelPath = path.resolve(dirname(fileURLToPath(import.meta.url)), '..');

function addMapping (router, mapping) {
  for (let url in mapping) {
    console.log(url);
    urlArray.push(url);
    if (url.startsWith('GET ')) {
      let path = url.substring(4);
      router.get(path, mapping[url]);
      // console.log(`register URL mapping: GET ${path}`);
    } else if (url.startsWith('POST ')) {
      let path = url.substring(5);
      router.post(path, mapping[url]);
      // console.log(`register URL mapping: POST ${path}`);
    } else if (url.startsWith('PUT ')) {
      let path = url.substring(4);
      router.put(path, mapping[url]);
      // console.log(`register URL mapping: PUT ${path}`);
    } else if (url.startsWith('DELETE ')) {
      let path = url.substring(7);
      router.del(path, mapping[url]);
      // console.log(`register URL mapping: DELETE ${path}`);
    } else {
      console.log(`invalid URL: ${url}`);
    }
  }
}

/* 获取所有dir文件夹下以.js结尾的文件 */
function addControllers (router, dir) {
  /* 同步函数读取文件夹中的文件 */
  fs.readdirSync(upperLevelPath + '/' + dir).filter((f) => {
    return f.endsWith('.js');
  }).forEach(async (f) => {
    let mapping = await import(upperLevelPath + '/' + dir + '/' + f)
    console.log(mapping.default);
    addMapping(router, mapping.default);
  });
  /* 用于检验是否有重复的路由 */
  let urlSet = new Set(urlArray);
  if (urlArray.length !== urlSet.size) {
    throw ('注意有重复的路由');
  }
  console.log(urlArray);
}

export function controller (dir) {
  /* 默认是controllers文件夹下的所有js文件 */
  let controllers_dir = dir || 'controllers';

  addControllers(router, controllers_dir);
  return router.routes();
}

export function allowedMethods () {
  return router.allowedMethods()
}
// module.exports = function (dir) {
//   let
//     controllers_dir = dir || 'controllers',
//     router = require('koa-router')();
//   addControllers(router, controllers_dir);
//   return router.routes();
// };
// export const controller = routes;
// export const allowedMethods = allowedMethods;
// export default {
//   controller: routes,
//   allowedMethods
// }